import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mahjong/const/CacheConst.dart';
import 'package:mahjong/const/MahjongConst.dart';
import 'package:mahjong/entity/Restful.dart';
import 'package:mahjong/entity/UserEntityInfo.dart';
import 'package:mahjong/entity/meta/MetaRoomEntity.dart';
import 'package:mahjong/page/UserLoginWidget.dart';
import 'package:mahjong/page/common/XpockerTips.dart';
import 'package:mahjong/page/dialog/Confirm.dart';
import 'package:mahjong/util/CustomerDialog.dart';
import 'package:mahjong/util/InsertHome.dart';
import 'package:mahjong/util/CacheUtil.dart';
import 'package:mahjong/util/CustomRoute.dart';
import 'package:mahjong/util/DictionaryConst.dart';
import 'package:mahjong/util/Http.dart';
import 'package:mahjong/util/ProviderClean.dart';
import 'package:mahjong/widget/Bubble.dart';
import 'package:mahjong/widget/dialog/AddHomeDialog.dart';
import 'package:mahjong/widget/dialog/CreateHomeDialog.dart';
import 'package:mahjong/widget/BubbleWidget.dart';
import 'package:mahjong/page/mahjong/dialog/RecordDialog.dart';
import 'package:mahjong/widget/dialog/PopMenus.dart';
import 'package:mahjong/page/mahjong/dialog/UserInfoDialog.dart';
import 'package:provider/provider.dart';

class GameIndex extends StatefulWidget {
  @override
  _GameIndexState createState() => _GameIndexState();
}

class BottomItem {
  IconData icon;
  String name;
  Function action;
  static void defaultAction() {}

  BottomItem.init({this.icon, this.name, this.action: defaultAction});
}

class _GameIndexState extends State<GameIndex> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  void _handlerDrawerButton() {
    _scaffoldKey.currentState.openEndDrawer();
  }

  void _showRecord() {
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return RecordDialog();
        });
  }

  void _loginOut() {
    CacheUtil.preferencesInstance.remove(CacheConst.userInfo);

    Navigator.of(context).pushAndRemoveUntil(
        new CustomRoute(UserLoginWidget(), AnimationEnum.zoom),
        (route) => route == null);
  }

  // 底部菜单
  List<BottomItem> _bottomItemList;
  // 侧拉菜单
  List<BottomItem> _drawItemList;
  ScrollController _scrollController = new ScrollController();

  @override
  void initState() {
    super.initState();
    _bottomItemList = [
      BottomItem.init(icon: Icons.car_rental, name: '战绩', action: _showRecord),
      BottomItem.init(
          icon: Icons.menu, name: '菜单', action: _handlerDrawerButton)
    ];
    _drawItemList = [
      BottomItem.init(icon: Icons.exit_to_app, name: '退出', action: _loginOut),
    ];
    _scrollController.addListener(() {
      if (_scrollController.offset ==
          _scrollController.position.maxScrollExtent) {
        _scrollController.jumpTo(0);
        Future.delayed(Duration(seconds: 1), () {
          textRoll();
        });
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((context) {
      // 检查用户是否在房间内
      Http.getInstance().request<Restful>(DictionaryConst.getRoom,
          success: (data) {
        if (data.body != null) {
          Map roomInfo = Map.castFrom(data.body);
          InsertHome.addHome(
              this.context, roomInfo["roomType"], roomInfo["code"]);
        }
      });
      textRoll();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  void textRoll() {
    _scrollController.animateTo(
      _scrollController.position.maxScrollExtent, //滚动到底部
      duration: const Duration(seconds: 20),
      curve: Curves.easeOut,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      endDrawer: Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.centerRight,
                end: Alignment.centerLeft,
                stops: [
              0.0,
              1.0
            ], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: [
              Color.fromARGB(255, 0, 0, 0),
              Color.fromARGB(20, 36, 41, 46)
            ])),
        width: ScreenUtil().screenWidth / 4,
        child: ListView(
            children: _drawItemList
                .map((ditem) => ElevatedButton(
                    style: ButtonStyle(
                      minimumSize: MaterialStateProperty.all(
                          Size(0, ScreenUtil().screenHeight / 8)),
                      backgroundColor:
                          MaterialStateProperty.resolveWith((states) {
                        //设置按下时的背景颜色
                        if (states.contains(MaterialState.pressed)) {
                          return Colors.blue[200];
                        }
                        //默认不使用背景颜色
                        return Colors.white.withOpacity(0);
                      }),
                      elevation: MaterialStateProperty.all(0),
                    ),
                    onPressed: ditem.action,
                    child: ListTile(
                        title: Text(
                          ditem.name,
                          style: TextStyle(color: Colors.white),
                        ),
                        leading: Icon(
                          ditem.icon,
                          color: Colors.white,
                        ))))
                .toList()),
      ),
      body: Stack(children: [
        // 背景
        Positioned(
            child: Container(
          width: double.infinity,
          height: double.infinity,
          child: Image.asset(
            "images/mahjong/background/home_bg3.png",
            fit: BoxFit.fill,
          ),
        )),
        //第二部分 第二层 气泡
        BubbleWidget(),
        //第三部分 高斯模糊
        buildBlureWidget(),
        // 底部 透明背景条
        Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              alignment: Alignment.centerRight,
              height: 50.h,
              width: ScreenUtil().screenWidth,
              padding: EdgeInsets.symmetric(horizontal: 20.h),
              decoration: BoxDecoration(
                  color: Colors.grey.withOpacity(0.4),
                  borderRadius: BorderRadius.circular(5)),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: _bottomItemList
                      .map((bitem) => Row(children: [
                            Material(
                                color: Colors.white.withOpacity(0),
                                child: Ink(
                                    child: InkWell(
                                        splashColor: Colors.orange,
                                        onTap: bitem.action,
                                        child: Container(
                                          decoration: BoxDecoration(
                                            color:
                                                Colors.black.withOpacity(0.4),
                                          ),
                                          padding: EdgeInsets.symmetric(
                                              vertical: 2.h, horizontal: 20.w),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceEvenly,
                                            children: [
                                              Icon(
                                                bitem.icon,
                                                color: Colors.white,
                                                size: 18.sp,
                                              ),
                                              SizedBox(width: 10.h),
                                              Text(
                                                bitem.name,
                                                style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 20.sp,
                                                ),
                                              )
                                            ],
                                          ),
                                        )))),
                            SizedBox(width: 30.w)
                          ]))
                      .toList()),
            )),

        Positioned(
            top: 10.h,
            left: 60.w,
            child: Container(
              alignment: Alignment.center,
              height: 40.h,
              width: 200.w,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(5.5),
                  child: ShaderMask(
                    shaderCallback: (Rect bounds) {
                      return LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Colors.transparent,
                            Colors.transparent,
                            Colors.orange,
                            Colors.black.withOpacity(0.2)
                          ],
                          stops: [
                            0,
                            .6,
                            .95,
                            1
                          ]).createShader(bounds);
                    },
                    blendMode: BlendMode.color,
                    child: Image.asset(
                      "images/logo/logo.png",
                      fit: BoxFit.fill,
                    ),
                  )),
            )),
        Consumer(builder:
            (BuildContext buildContext, UserEntityInfo provider, Widget child) {
          return //  头像部分
              Positioned(
            top: 60.h,
            bottom: 60.h,
            left: 60.w,
            child: Container(
              padding: EdgeInsets.all(10.w),
              height: double.infinity,
              width: 200.w,
              decoration: BoxDecoration(
                  color: Colors.grey.withOpacity(0.4),
                  borderRadius: BorderRadius.circular(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      InkWell(
                        child: Container(
                            width: 70.w,
                            height: 70.w,
                            decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                border: Border.all(
                                    color: Colors.white, width: 1.w)),
                            child: ClipOval(
                              child: provider.sysUser.portraitUrl == null
                                  ? Image.asset(
                                      "images/mahjong/user/header/common_header.png",
                                      fit: BoxFit.cover,
                                    )
                                  : CachedNetworkImage(
                                      width: double.infinity,
                                      height: double.infinity,
                                      fit: BoxFit.cover,
                                      placeholder: (context, url) =>
                                          CircularProgressIndicator(),
                                      errorWidget: (context, url, error) =>
                                          Icon(Icons.error),
                                      imageUrl: DictionaryConst.filePath +
                                          provider.sysUser.portraitUrl,
                                    ),
                            )),
                        onTap: () async {
                          showDialog<Null>(
                              context: context,
                              barrierDismissible: false,
                              builder: (BuildContext context) {
                                return UserInfoDialog(
                                    title: 'title', description: 'description');
                              });
                        },
                      ),
                      Expanded(
                          child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text(
                            provider.sysUser.username,
                            style:
                                TextStyle(color: Colors.white, fontSize: 14.sp),
                          ),
                          Text(
                            'ID:' + provider.sysUser.id.toString(),
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                                fontWeight: FontWeight.bold),
                          )
                        ],
                      ))
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Expanded(
                        child: buildRoomWidget("创建房间", Colors.green, () {
                          showDialog<Null>(
                              context: context,
                              barrierDismissible: false,
                              builder: (BuildContext context) {
                                return CreateHomeDialog(
                                    title: 'title', description: 'description');
                              });
                        }),
                      ),
                      buildRoomWidget("加入", Colors.orange, () {
                        showDialog<Null>(
                            context: context,
                            barrierDismissible: false,
                            builder: (BuildContext context) {
                              return AddHomeDialog(callback: (roomCode) {
                                Http.getInstance().request<Restful>(
                                    DictionaryConst.addRoom,
                                    type: RequestEnum.POST,
                                    contentType: ContentType.text,
                                    loadingMsg: "查找房间中...",
                                    showLoading: true,
                                    responseType: ResponseType.json,
                                    showErrorMsg: true,
                                    data: {"roomCode": roomCode},
                                    success: (result) {
                                  ProviderClean.cleanAll();
                                  InsertHome.addHome(
                                      context, result.body, roomCode);
                                }, error: (result) {
                                  print("-----------------------");
                                });
                              });
                            });
                      }),
                    ],
                  )
                ],
              ),
            ),
          );
        }),
        // TIPS

        Positioned(
          top: 30.h,
          right: 60.w,
          child: Container(
            height: 30.h,
            width: 400.w,
            padding: EdgeInsets.symmetric(horizontal: 10.h),
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              color: Colors.grey.withOpacity(0.4),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.volume_up,
                  color: Colors.white,
                ),
                SizedBox(width: 10.w),
                Expanded(
                    child: SingleChildScrollView(
                        controller: _scrollController,
                        scrollDirection: Axis.horizontal,
                        child: Container(
                            child: Text(
                          "此平台仅用于学习交流,严禁赌博!!! 如有发现赌博行为将立即封号,并将信息发送给本地公安,请广大玩家遵守法律。",
                          maxLines: 1,
                          style: TextStyle(color: Colors.white),
                        ))))
              ],
            ),
          ),
        ),
        // 广告位置
        Positioned(
          top: 60.h,
          bottom: 60.h,
          right: 60.h,
          child: Container(
            padding: EdgeInsets.all(10.h),
            height: double.infinity,
            width: 400.w,
            child: GridView(
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.symmetric(vertical: 0),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 5, //每一行的列数
                mainAxisSpacing: 5, //主轴方向上的间距
                crossAxisSpacing: 10, //交叉轴轴方向上的间距
                childAspectRatio: 1,
              ),
              children: ["广", "告", "位", "置", "招", "租"]
                  .map((item) => Material(
                      color: Colors.white.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(5.00),
                      child: Ink(
                          //设置背景 默认矩形
                          child: InkWell(
                              onTap: () {
                                /*  CustomerDialog.showRoomMessage(".."); */
                              },
                              splashColor: Colors.black,
                              child: Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(5.00),
                                  border: Border.all(
                                      color: Colors.black.withOpacity(0.3)),
                                ),
                                child: Center(
                                    child: Text(
                                  item.toString(),
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: ScreenUtil().setSp(30),
                                      fontWeight: FontWeight.bold),
                                )),
                              )))))
                  .toList(),
            ),
          ),
        )
      ]),
    );
  }

  Widget buildRoomWidget(
      String actionName, Color background, Function doAction) {
    return OutlinedButton(
      style: ButtonStyle(
        minimumSize:
            MaterialStateProperty.all(Size(0, ScreenUtil().screenHeight / 8)),
        backgroundColor: MaterialStateProperty.resolveWith((states) {
          //设置按下时的背景颜色
          if (states.contains(MaterialState.pressed)) {
            return Colors.blue[200];
          }
          //默认不使用背景颜色
          return background;
        }),
        elevation: MaterialStateProperty.all(0),
        // shape: MaterialStateProperty.all(StadiumBorder()),
      ),
      onPressed: doAction,
      child: Text(
        actionName,
        style: TextStyle(
            fontSize: 15.sp, fontWeight: FontWeight.w800, color: Colors.white),
      ),
    );
  }
}

//第三部分 高斯模糊
Widget buildBlureWidget() {
  return BackdropFilter(
    filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
    child: Container(
      color: Colors.white.withOpacity(0.1),
    ),
  );
}
